/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pfc.modeloer;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.ddlutils.model.ForeignKey;
import org.apache.ddlutils.model.Reference;
import org.apache.ddlutils.model.Table;

/**
 *
 * @author xandru
 */
public class ERReferences {

    //private ArrayList<ERReference> ref;
    private Set<ERReference> ref;

    public ERReferences() {
        //ref = new ArrayList<ERReference>();
        ref = new LinkedHashSet<ERReference>();
    }


    public void add(ERReference r)
    {
        ref.add(r);
    }

    public Collection<ERReference> getSourceTableReferences(String source)
    {
        ArrayList<ERReference> l = new ArrayList<ERReference>();
        for (ERReference r: ref)
        {
            if (StringUtils.equals(r.sourceEntity.getName(),source))
            {
                l.add(r);
            }
        }

        return l;
    }

    public Collection<ERReference> getTargetTableReferences(String target)
    {
        ArrayList<ERReference> l = new ArrayList<ERReference>();
        for (ERReference r: ref)
        {
            if (StringUtils.equals(r.targetEntity.getName(), target))
            {
                l.add(r);
            }
        }

        return l;
    }

     void addTableReferences(ERModel m,Table t) {
         ERReference r = null;
         EREntity s = m.findEntity(t.getName());


         if (t.getForeignKeyCount()==0)
             return;

         //r.setTablaOrigen(t.getName());

        for (ForeignKey f : t.getForeignKeys())
        {
            EREntity d = m.findEntity(f.getForeignTableName());
            ERAttrib sa = null,ta = null;
            //System.out.println("kk " + t.getName() + " ->" + d);
            for (Reference ref : f.getReferences())
            {
                sa = s.findAttrib(ref.getLocalColumnName());
                ta = d.findAttrib(ref.getForeignColumnName());
            }

            r = new ERReference(s,d,sa,ta);
        }
        
        ref.add(r);

        //System.out.println("addTableReference [" + r.tablaOrigen + "] -> " + "[" + r.tablaDestino + "]");
    }


    @Override
    public String toString()
    {
        String cad="";
        for (ERReference r: ref)
        {
            cad +="\nERReferences [" + r.getSourceEntity() + "] -> [" + r.getTargetEntity() + "]";
        }


        return cad;
     }

}
